//
//  EditViewModel.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/25/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import Foundation

typealias EditDetailsCellConfigurator = TableCellConfigurator<EditDetailsCell, String?>
typealias EditActionsCellConfigurator = TableCellConfigurator<EditActionsCell, Any?>
typealias EditMainCellConfigurator = TableCellConfigurator<EditMainCell, EditViewModel.EditMainItem>


final class EditViewModel {
    
    struct EditMainItem {
        var price: Int?
        var rule: RuleType?
        
        // битый или на ходу

        var rastomozhen: Bool = false
        var isObmen: Bool = false
    }
    
    
    var items: [CellConfigurator] = []
    
    private let backendService = Backend()
    
    init (post: Post) {
        
        let mainItem = EditMainItem(price: post.price, rule: post.ruleType, rastomozhen: post.isRastomozhen, isObmen: post.isObmen)
        
        items = [
            CarHeaderCellConfigurator(item: MainViewModel.CarHeader(postModel: PostModel(post: post))),
            EditMainCellConfigurator(item: mainItem),
            EditDetailsCellConfigurator(item: post.description),
            CarContactsCellConfigurator(item: MainViewModel.CarContacts(city: post.city, name: post.contactName, email: post.contactEmail)),
            EditActionsCellConfigurator(item: nil)
        ]
    }
    
    public func updateOptions (options: [String:Any], id: Int, completion: @escaping (Result<Bool, RequestError>) -> Void) {
        var request = URLRequest(url: Request(base: .advert).getUrl(path: "cars/custom-options/\(id)/"))
        
        if let optionsBody = try? JSONSerialization.data(withJSONObject: options, options: []) {
            request.httpBody = optionsBody
            request.httpMethod = "PATCH"
            
            
            print(request)
            
            backendService.fetchFromBackend(for: Bool.self, request: request, statusCode: 200, sendBool: true) { (result) in
                switch result {
                case .failure(let err):
                    completion(.failure(err))
                case .success(_):
                    completion(.success(true))
                }
            }
        } else {
            completion(.failure(.general))
        }
    }
    
    public func updateAdvert (id: Int,
                              city: City?,
                              contact_name: String?,
                              contact_email: String?,
                              description: String?,
                              mainData: EditViewModel.EditMainItem,
                              completion: @escaping (Result<Bool, RequestError>) -> Void) {
        var request = URLRequest(url: Request(base: .advert).getUrl(path: "adverts/my/\(id)/"))
        let parameters = ["city": city?.id as Any?,
                          "contact_name": contact_name,
                          "contact_email": contact_email,
                          "description": description,
                          "exchange": mainData.isObmen,
                          "rule_type": mainData.rule?.value,
                          "cleared_by_customs": mainData.rastomozhen]
        let body = self.returnParameters(parameters)
        request.httpMethod = "PATCH"
        
        if let postData = try? JSONSerialization.data(withJSONObject: body, options: []) {
            request.httpBody = postData
            
            backendService.fetchFromBackend(for: Bool.self, request: request, statusCode: 200, sendBool: true) { (result) in
                switch result {
                case .failure(let err):
                    completion(.failure(err))
                case .success(_):
                    completion(.success(true))
                }
            }
        } else {
            completion(.failure(.general))
        }
    }
    
    private func returnParameters (_ data: [String:Any?]) -> [String:Any] {
        var output: [String:Any] = [:]
        
        for key in data.keys {
            if let item = data[key] {
                if item != nil {
                    output[key] = item
                }
            }
        }

        return output
    }
}
